<template>
	<view class="message">
		<view class="message_notification">
			<view class="notification">
				<view @click="gotorecruit">
					<view class="recruit">
						<image src="../../static/image/message/recruit.png"></image>
						<view class="num" v-if="msg_num>0">{{msg_num}}</view>
					</view>
					<text>劳务招聘</text>
				</view>
				<view @click="gotonotice">
					<view class="recruit notice">
						<image src="../../static/image/message/notice.png"></image>
						<view class="num" v-if="message_noReadNum>0">{{message_noReadNum}}</view>
					</view>
					<text>系统通知</text>
				</view>
				<view @click="gotoremind">
					<view class="recruit remind">
						<image src="../../static/image/message/remind.png"></image>
						<view class="num" v-if="notice_noReadNum>0">{{notice_noReadNum}}</view>
					</view>
					<text>提醒</text>
				</view>
			</view>
		</view>
		<view class="msg_list" v-if="showindex==0">
			<view v-for="(item,index) in datalist" :key="index">
				<messageItem :msgitem="item" @updatenum="updatenum"></messageItem>
			</view>
			<view v-if="datalist.length<1">
				<image
					style="position: absolute;top:0;left: 0;bottom: 0;right: 0;margin: auto;width: 600rpx;"
					src="../../static/image/no-data.png" mode=""></image>
			</view>
		</view>
		<view class="msg_list" v-else-if="showindex==1">
			<view class="msg_item" v-for="(item,index) in messageList" :key="item.id" @click="messageRead(item)">
				<view class="msg_l">
					<image src="../../static/image/message/notice.png"></image>
				</view>
				<view class="msg_r">
					<view class="msg_text"><text class="msg_content">{{item.name}}</text><text>{{item.msg_create_date}}</text></view>
					<view class="msg_detail unread">
						<text class="max_content">{{item.content}}</text>
						<text class="spot" v-if="item.state=='未读'"></text>
					</view>
				</view>
			</view>
			<view v-if="messageList.length<1">
				<image
					style="position: absolute;top:0;left: 0;bottom: 0;right: 0;margin: auto;width: 600rpx;"
					src="../../static/image/no-data.png" mode=""></image>
			</view>
		</view>
		<view class="msg_list" v-else>
			<view class="msg_item" v-for="(item,index) in noticeList" :key="item.id" @click="gotodetail(item)">
				<view class="msg_l">
					<image src="../../static/image/message/remind.png"></image>
				</view>
				<view class="msg_r">
					<view class="msg_text">
						<view class="max_name">
							<text>{{item.name}}</text>
							<text class="spot" v-if="item.state=='未读'"></text>
						</view>
						<text>{{item.msg_create_date}}</text>
					</view>
				</view>
			</view>
			<view v-if="noticeList.length<1">
				<image
					style="position: absolute;top:0;left: 0;bottom: 0;right: 0;margin: auto;width: 600rpx;"
					src="../../static/image/no-data.png" mode=""></image>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/static/js/api.js'
	import uniTabs from '@/components/v-tabs/v-tabs.vue'
	import messageItem from './messageItem.vue'

	import {
		share
	} from '@/mixins/index.js'
	export default {
		mixins: [share],
		components: {
			uniTabs,
			messageItem
		},
		data() {
			return {
				showindex:0,
				tabs: [
					'系统通知',
					'提醒',
				],
				messageList: [],
				message_noReadNum: '',
				notice_noReadNum: '',
				msg_num: '',
				noticeList: [],
				activeIndex: 1,
				userinfo: '',
				datalist: [],
				datalist1: [],
				reciver_id: '' ,//接收人id
				is_open_socket: false,
				unread_message:[],//未读消息
				reconnection:false
			}
		},
		onLoad() {
			// if (uni.getStorageSync('dataNum')) {
			// 	let dataNum = uni.getStorageSync('dataNum')
			// }
			if (uni.getStorageSync('userInfo')&&JSON.parse(uni.getStorageSync('userInfo')).account_type!=''&&!uni.getStorageSync('closeWebsocket')) {
				this.socketTask = uni.connectSocket({
					url: "ws://39.99.161.175:9001/socket/list",
					// url: "ws://192.168.0.134:9001/socket/list",
					success(data) {
						console.log(data, '创建成功')
					},
					fail(err) {
						console.log(err,'创建失败');
					}
				});
				this.socketTask.onOpen((res) => {
					console.log('连接已打开', res);
					this.is_open_socket = true;
					var data = JSON.stringify({uid:JSON.parse(uni.getStorageSync('userInfo')).uid})
					this.sendMessage(data)
					this.onSocketMessage()
				});
			}else {
				this.datalist = []
			}
		},
		onShow() {
			this.message_noReadNum = ''
			this.notice_noReadNum = ''
			if (uni.getStorageSync('userInfo')) {
				this.userinfo = JSON.parse(uni.getStorageSync('userInfo'));
				// if (this.userinfo.is_confirm == 'True') {
					this.getMessage()
					this.getNotice()
				// }
			} else {
				this.msg_num = ''
				this.datalist = []
			}
			setTimeout(()=>{
				// console.log(this.socketTask);
				if(this.socketTask&&this.socketTask.readyState!=1){
					this.socketTask = uni.connectSocket({
						url: "ws://39.99.161.175:9001/socket/list",
						// url: "ws://192.168.0.134:9001/socket/list",
						success(data) {
							console.log(data, '创建成功')
						},
						fail(err) {
							console.log(err,'创建失败');
						}
					});
					this.socketTask.onOpen((res) => {
						console.log('连接已打开', res);
						this.is_open_socket = true;
						var data = JSON.stringify({uid:JSON.parse(uni.getStorageSync('userInfo')).uid})
						this.reconnection = true
						this.datalist = []
						this.sendMessage(data)
						this.onSocketMessage()
					});
				}
			},500)
		},
		//点击tabbar
		onTabItemTap(){
			// debugger
			if(uni.getStorageSync('userInfo')&&uni.getStorageSync('closeWebsocket')&&JSON.parse(uni.getStorageSync('userInfo')).account_type!=''){
				uni.setStorageSync('closeWebsocket', false)
				this.socketTask = uni.connectSocket({
					url: "ws://39.99.161.175:9001/socket/list",
					// url: "ws://192.168.0.134:9001/socket/list",
					success(data) {
						console.log(data, '创建成功')
					},
					fail(err) {
						console.log(err,'创建失败');
					}
				});
				this.socketTask.onOpen((res) => {
					console.log('连接已打开', res);
					this.is_open_socket = true;
					var data = JSON.stringify({uid:JSON.parse(uni.getStorageSync('userInfo')).uid})
					this.sendMessage(data)
					this.onSocketMessage()
				});
			}
		},
		//断开连接
		// onHide(){
		// 	this.closeSocket();
		// },
		methods: {
			sendMessage(data){
				if (this.is_open_socket) {
					// websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
					this.socketTask.send({
						data,
						async success() {
							console.log("消息发送成功");
						},
					});
				}
			},
			//监听返回的信息
			onSocketMessage (){
				var that = this;
				var num = 0
				this.socketTask.onMessage((res) => {
					console.log(JSON.parse(res.data));
					if(JSON.parse(res.data).length>0){
						// if(this.reconnection){
						// 	that.datalist = []
						// }
						var msgs = JSON.parse(res.data)
						var test_msg = JSON.parse(res.data)
						var new_arr = []
						test_msg.forEach((item,index)=>{
							item.msg = JSON.parse(item.msg.replace(/\'/g, "\"").replace(/\\n/g, " ")).msg
							new_arr.push(item)
						})
						msgs.forEach(item => {
							var m = JSON.parse(item.msg.replace(/\'/g, "\""))
							if(m.msg==''&&m.order=='0'){
								item.msg='[订单已创建]'
							}else if(m.msg==''&&m.order=='1'){
								item.msg='[订单已完成]'
							}else{
								item.msg = JSON.parse(item.msg.replace(/\'/g, "\"").replace(/\\n/g, " ")).msg
							}
							num+=Number(item.unread_count)
						})
						// this.datalist = this.datalist.concat(msgs)
						this.datalist = msgs.concat(this.datalist)
						console.log("this.datalist:",this.datalist);
						this.msg_num = num
						setTimeout(()=>{
							this.merge_array()
						},100)
					}	
					if(JSON.parse(res.data).constructor==Object&&JSON.parse(res.data).uid){
						var single_message = JSON.parse(res.data)
						if(single_message.msg==''&&single_message.order=='0'){
							single_message.msg='订单已创建'
						}
						if(single_message.msg==''&&single_message.order=='1'){
							single_message.msg='订单已完成'
						}
						this.datalist.forEach((item,index) => {
							if(item.user_id==single_message.uid&&item.reciver_id==single_message.reciver_id&&item.work_id==single_message.work_id&&item.recruit_id==single_message.recruit_id){
								item.msg = JSON.parse(JSON.stringify(single_message.msg).replace(/\\n/g, " "))
								item.msg_create_date = single_message.time
								item.unread_count += single_message.unread_count
							}
							if(item.user_id==single_message.reciver_id&&item.reciver_id==single_message.uid&&item.work_id==single_message.work_id&&item.recruit_id==single_message.recruit_id){
								item.msg = JSON.parse(JSON.stringify(single_message.msg).replace(/\\n/g, " "))
								item.msg_create_date = single_message.time
								item.unread_count += single_message.unread_count
							}
						})
						this.msg_num += single_message.unread_count
						setTimeout(()=>{
							this.merge_array()
						},100)
					}
				});
			},
			//关闭
			closeSocket() {
				var that = this;
				this.socketTask.close({
					success(res) {
						that.is_open_socket = false;
						console.log("关闭成功", res)
					},
					fail(err) {
						console.log("关闭失败", err)
					}
				})
			},
			gotorecruit() {
				if (uni.getStorageSync('userInfo')) {
					// if (this.userinfo.is_confirm == 'True') {
						this.showindex = 0
					// 	// uni.navigateTo({
					// 	// 	url: '../../pagesB/message/recruitmentList'
					// 	// })
					// } else {
					// 	uni.showToast({
					// 		icon: 'none',
					// 		title: '请先实名认证'
					// 	})
					// }
				} else {
					uni.showToast({
						icon: 'none',
						title: '请登录'
					})
				}
			},
			gotonotice() {
				if (uni.getStorageSync('userInfo')) {
					// if (this.userinfo.is_confirm == 'True') {
					// 	// uni.navigateTo({
					// 	// 	url: '../../pagesB/message/notificationList'
					// 	// })
						this.showindex = 1
					// } else {
					// 	uni.showToast({
					// 		icon: 'none',
					// 		title: '请先实名认证'
					// 	})
					// }
				} else {
					uni.showToast({
						icon: 'none',
						title: '请登录'
					})
				}
			},
			gotoremind() {
				if (uni.getStorageSync('userInfo')) {
					// if (this.userinfo.is_confirm == 'True') {
					// 	// uni.navigateTo({
					// 	// 	url: '../../pagesB/message/reminderList'
					// 	// })
						this.showindex = 2
					// } else {
					// 	uni.showToast({
					// 		icon: 'none',
					// 		title: '请先实名认证'
					// 	})
					// }
				} else {
					uni.showToast({
						icon: 'none',
						title: '请登录'
					})
				}
			},
			//系统通知
			getMessage() {
				api.messageList('system.notice', '_api_search_all', this.userinfo.access_token, this
					.userinfo.uid, 1000, 1).then(res => {
					if(res.errcode == 1001){
						this.datalist = []
						this.closeSocket();
					}
					if (res.data.length > 0) {
						var arr = JSON.parse(JSON.stringify(res.data).replace(/date/g, "msg_create_date"))
						arr.forEach(item=>{
							item.content = JSON.stringify(item.content.replace(/\↵/g, " ").replace(/\\n/g, " "))
						})
						this.messageList = arr 
						this.message_noReadNum = Number((res.data.filter(v => v.state == '未读')).length)
					}
				})
				// .catch(e => {
				// 	uni.showToast({
				// 		icon: 'none',
				// 		title: e.message
				// 	})
				// })
			},
			//提醒
			getNotice() {
				api.messageList('message.remind', '_api_search_user', this.userinfo.access_token, this
					.userinfo.uid, 1000, 1).then(res => {
					if(res.errcode == 1001){
						this.datalist = []
						this.closeSocket();
					}
					if (res.data.length > 0) {
						var arr = JSON.parse(JSON.stringify(res.data).replace(/date/g, "msg_create_date"))
						this.noticeList = arr
						this.notice_noReadNum = Number((res.data.filter(v => v.state == '未读')).length)
					}
				})
				// .catch(e => {
				// 	uni.showToast({
				// 		icon: 'none',
				// 		title: e.message
				// 	})
				// })
			},
			//比较时间
			compareDate(d1, d2) {
				return ((new Date(d1.replace(/-/g, "\/"))) > (new Date(d2.replace(/-/g, "\/"))));
			},
			//合并消息
			merge_array(){
				// setTimeout(()=>{
				// 	this.msg_num = 0
				// 	this.datalist.forEach(item=>{
				// 		this.msg_num+=Number(item.unread_count)
				// 	})
				// 	this.datalist = this.datalist.sort(function(a, b) {
				// 		return a.msg_create_date < b.msg_create_date ? 1 : -1
				// 	})
				// })
				this.msg_num = 0
				this.datalist.forEach(item=>{
					this.msg_num+=Number(item.unread_count)
				})
				this.datalist = this.datalist.sort(function(a, b) {
					return a.msg_create_date < b.msg_create_date ? 1 : -1
				})
			},
			//是否包含
			includes(arr1, arr2) {
			  return arr2.every(val => arr1.includes(val));
			},
			//修改已读消息
			updatenum(msgitem){
				if(this.showindex==0){
					this.datalist.forEach(item=>{
						if(item.user_id==msgitem.user_id&&item.reciver_id==msgitem.reciver_id&&item.work_id==msgitem.work_id&&item.recruit_id==msgitem.recruit_id){
							this.msg_num -= item.unread_count
							item.unread_count = 0
						}
					})
				}
			},
			//系统通知详情
			messageRead(item) {
				api.messageRead('system.notice', '_api_onchange_read', this.userinfo.access_token, this
					.userinfo.uid, item.id).then(res => {
					uni.setStorageSync('messageDetail', JSON.stringify(item))
					uni.navigateTo({
						url: '../../pagesB/message/messageDetail'
					})
				}).catch(e => {
					uni.showToast({
						icon: 'none',
						title: e.message
					})
				})
			},
			gotodetail(item){
				api.messageRead('message.remind', '_api_browse_read_state', this.userinfo.access_token, this
					.userinfo.uid, item.id).then(res => {
					uni.setStorageSync('messageDetail', JSON.stringify(item))
					uni.navigateTo({
						url: '../../pagesB/message/messageDetail'
					})
				}).catch(e => {
					uni.showToast({
						icon: 'none',
						title: e.message
					})
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	.message {
		.unred_text {
			position: relative;

			.noReadIcon {
				width: 15rpx;
				height: 15rpx;
				background-color: #B8212B;
				border-radius: 50%;
				position: absolute;
			}
		}

		width: 100%;
		height: 100vh;
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		z-index: 1;
		overflow: hidden;
		width: 100%;
		height: 100%;
		margin: 0 auto;
		box-sizing: border-box;

		.head_nav {
			width: 100%;
			display: flex;
			justify-content: space-between;
			background-color: #fff;
			// position: absolute;
			// top: 0;
			// left: 0;
			// right: 0;
			z-index: 1000;
			width: 100%;
			border-bottom: 2rpx solid #dfdfdf;
			box-shadow: 1rpx 0rpx 1rpx 0rpx #dfdfdf;

			.nav_item {
				width: 50%;
				text-align: center;
				margin: 20rpx 0;
				border-right: 2rpx solid #dfdfdf;
				position: relative;
				font-size: 16px;
				line-height: 40rpx;

				.messageIcon {
					width: 35rpx;
					height: 35rpx;
					background-color: #B8212B;
					border-radius: 50%;
					line-height: 35rpx;
					text-align: center;
					font-size: 10px;
					color: #fff;
					position: absolute;
					right: 22%;
					bottom: 10%;
				}

				.message_notice {
					right: 30%;
				}
			}

			.nav_notice_active {
				color: #B8212B;
			}

			.nav_tell_active {
				color: #B8212B;
			}
		}
	}

	.view_content {
		overflow-y: scroll;
		position: absolute;
		width: 100%;
		height: 100%;

		.unred {
			.unred_top {
				padding: 30rpx;
				display: flex;
				background-color: #FFFFFF;
				margin: 20rpx;
				border-radius: 10rpx;
				border: 2rpx solid #dfdfdf;
				box-shadow: 1px 0px 1px 0px #dfdfdf;

				.unred_img {
					width: 100rpx;
					height: 100rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}

				.unred_text .text {
					margin-left: 20rpx;
					font-size: 28rpx;
					display: block;
				}

			}

			.unred_top:nth-child(1) {
				margin-top: 100rpx;
			}
		}
	}

	.message_notification {
		height: 245rpx;
		background: #B8212B; //E8002A
		padding: 38rpx 34rpx 0;
		border-radius: 0 0 20rpx 20rpx;
		position: relative;
		z-index: 999;

		.notification {
			width: 100%;
			background: #fff;
			display: flex;
			justify-content: space-between;
			box-shadow: 0px 0px 15rpx 0px rgba(0, 0, 0, 0.2);
			border-radius: 10rpx;
			padding: 44rpx 70rpx 38rpx;

			>view {
				display: flex;
				flex-direction: column;

				image {
					width: 100rpx;
					height: 100rpx;
				}

				text {
					font-size: 28rpx;
					color: #181818;
					margin-top: 16rpx;
					text-align: center;
				}

				.recruit {
					position: relative;

					.num {
						background: #FD2218;
						padding: 2rpx 10rpx;
						border-radius: 50%;
						font-size: 26rpx;
						font-weight: 500;
						color: #fff;
						border: 3rpx solid #fff;
						position: absolute;
						top: 0;
						right: 0;
						transform: translate(0%, -50%);
					}
				}

			}
		}
	}

	.msg_list {
		padding: 54rpx 38rpx 20rpx;
		height: calc(100% - 245rpx);
		overflow-y: auto;

		.msg_item {
			height: 166rpx;
			display: flex;
			align-items: center;

			.msg_l {
				image {
					width: 94rpx;
					height: 94rpx;
					border-radius: 50%;
				}
			}

			.msg_r {
				width: 100%;
				height: 100%;
				display: flex;
				flex-direction: column;
				justify-content: center;
				border-bottom: 2rpx solid #D8D8D8;
				margin-left: 26rpx;

				.msg_text {
					font-size: 32rpx;
					color: #181818;
					display: flex;
					align-items: center;
					justify-content: space-between;

					text:nth-child(2) {
						font-size: 26rpx;
						color: #999999;
					}
				}

				.msg_detail {
					font-size: 28rpx;
					color: #666666;
					max-width: 545rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					margin-top: 15rpx;
				}
				.unread{
					display: flex;
					align-items: center;
					justify-content: space-between;
				}
				.max_content{
					max-width: 500rpx;
					text-overflow: ellipsis;
					white-space: nowrap;
					overflow: hidden;
				}
				.msg_content{
				  word-break: break-all;
					max-width: 280rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
				.max_name{
					display: flex;
					word-break: break-all;
					max-width: 250rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					.spot{
						margin-left: 10rpx;
					}
				}
				.spot{
					width: 16rpx;
					height: 16rpx;
					border-radius: 50%;
					background: #FF3B30;
					display: inline-block;
				}
			}
		}
	}
</style>
